<template>
  <a-modal
    v-model:open="visible"
    title="编辑套餐"
    @ok="handleOk"
    @cancel="handleCancel"
    :confirmLoading="confirmLoading"
  >
    <a-form
      :model="formState"
      :rules="rules"
      ref="formRef"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
    >
      <a-form-item label="套餐名称" name="name">
        <a-input v-model:value="formState.name" placeholder="请输入套餐名称" />
      </a-form-item>

      <a-form-item label="积分值" name="point">
        <a-input-number
          v-model:value="formState.point"
          :min="0"
          :precision="0"
          placeholder="请输入积分值"
          style="width: 100%"
        />
      </a-form-item>

      <a-form-item label="价格" name="price">
        <a-input-number
          v-model:value="formState.price"
          :min="0"
          :precision="2"
          placeholder="请输入价格（元）"
          style="width: 100%"
        />
      </a-form-item>
      <a-form-item label="套餐封面" name="cover">
        <upload-component :value="formState.cover" @change="(url) => (formState.cover = url)" />
      </a-form-item>

      <a-form-item label="套餐状态" name="status">
        <a-switch
          v-model:checked="formState.status"
          checked-value="OPEN"
          un-checked-value="CLOSE"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import type { FormInstance } from 'ant-design-vue'
import uploadComponent from '@/components/uploadComponent.vue'
import type { FormState } from './type.dict'

const visible = ref(false)
const confirmLoading = ref(false)
const formRef = ref<FormInstance>()

const formState = ref<FormState>({
  name: '',
  price: 0,
  point: 0,
  cover: '',
  status: 'CLOSE',
  details: [],
})

const rules = {
  point: [
    { required: true, message: '请输入积分值', trigger: 'blur' },
    { type: 'number', message: '积分值必须为数字', trigger: 'blur' },
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', message: '价格必须为数字', trigger: 'blur' },
  ],
  name: [
    { required: true, message: '请输入套餐名称', trigger: 'blur' },
    { max: 50, message: '名称长度不能超过50个字符', trigger: 'blur' },
  ],
}
const emit = defineEmits(['update', 'cancel'])

const handleOk = async () => {
  try {
    await formRef.value?.validate()
    confirmLoading.value = true
    emit('update', formState.value)
    visible.value = false
    confirmLoading.value = false
  } catch (error) {
    console.error('验证失败:', error)
  }
}

const handleCancel = () => {
  visible.value = false
  emit('cancel')
}

const open = (record?: FormState) => {
  if (record) {
    formState.value = {
      ...record,
      price: record.price / 100,
    }
  } else {
    formState.value = {
      name: '',
      price: 0,
      point: 0,
      cover: '',
      status: 'CLOSE',
      details: [],
    }
  }
  visible.value = true
}

defineExpose({
  open,
})
</script>
